package com.seth.myapplication.surface;


import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import com.seth.myapplication.DataApp;
import com.seth.myapplication.MainActivity;
import com.seth.myapplication.R;
import com.seth.myapplication.bean.Rewords;
import com.seth.myapplication.bean.User;
import com.seth.myapplication.dialog.DatePickerFragment;
import com.seth.myapplication.dialog.ImagePickerFragment;
import com.seth.myapplication.dialog.TimePickerFragment;
import com.seth.myapplication.service.NetWorkService;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Seth on 2017/10/11.
 */

public class page2Fragment extends Fragment {
    public static final String RELEASE_TASK = "com.seth.myapplication.service.PUBLISH.TASK";
    public static final String PASS_USER = "mian_user";
    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_TIME = 1;
    private static final String DIALOG_DATE = "DialogDate";
    private static final String DIALOG_TIME = "DialogTime";

    private ImageView img1 = null;
    private ImageView img2 = null;
    private ImageView img3 = null;
    private ImageView img4 = null;

    private static Bitmap sBitmap;
    private static Uri sUri;
    private static File sFile;

    private ImageView img1_delete;
    private ImageView img2_delete;
    private ImageView img3_delete;
    private ImageView img4_delete;

    private File img1File;
    private File img2File;
    private File img3File;
    private File img4File;

    private Bitmap bitmap1;
    private Bitmap bitmap2;
    private Bitmap bitmap3;
    private Bitmap bitmap4;

    private RelativeLayout block1;
    private RelativeLayout block2;
    private RelativeLayout block3;
    private RelativeLayout block4;

    private static int imgStatus = 1;

    private Button setDeadDate;
    private Button setDeadTime;
    private Button releaseTask;
    private ViewGroup.LayoutParams params;
    private Date date = null;
    private String time1 = null, time2 = null;
    private EditText taskTitle;
    private EditText taskContent;
    private EditText taskPrice;
    private Spinner taskType;
    private CheckBox checkBox;

    private User mUser;
    private Rewords newRewords;
    private DataApp dataApp;

    private PublishBroadCast msgReceiver;


    private View view;


    public static void setImgBit(Bitmap bitmap) {
        sBitmap = bitmap;
    }

    public static void setImgUrl(Uri img_fileUrl) {
        sUri = img_fileUrl;
    }

    public static void setImgNu(int imgNu) {
         imgStatus = imgNu;
    }

    public static void setFile(File file) {
        sFile = file;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_new_task, container, false);
//        Bundle bundle = getArguments();
//        mUser = (User) bundle.getSerializable(PASS_USER);
        dataApp = (DataApp) getActivity().getApplication();
        initView(view);
        initEvent();


        return view;

    }

    private void initView(View view) {
        block1 = (RelativeLayout) view.findViewById(R.id.block_img1);
        block2 = (RelativeLayout) view.findViewById(R.id.block_img2);
        block3 = (RelativeLayout) view.findViewById(R.id.block_img3);
        block4 = (RelativeLayout) view.findViewById(R.id.block_img4);

        img1 = (ImageView) view.findViewById(R.id.task_img1);
        img2 = (ImageView) view.findViewById(R.id.task_img2);
        img3 = (ImageView) view.findViewById(R.id.task_img3);
        img4 = (ImageView) view.findViewById(R.id.task_img4);

        img1_delete = (ImageView) view.findViewById(R.id.task_img1_delete);
        img2_delete = (ImageView) view.findViewById(R.id.task_img2_delete);
        img3_delete = (ImageView) view.findViewById(R.id.task_img3_delete);
        img4_delete = (ImageView) view.findViewById(R.id.task_img4_delete);


        setDeadDate = (Button) view.findViewById(R.id.btn_dead_date);
        setDeadTime = (Button) view.findViewById(R.id.btn_dead_time);


        taskTitle = (EditText) view.findViewById(R.id.new_task_title);
        taskContent = (EditText) view.findViewById(R.id.new_task_content);
        taskPrice = (EditText) view.findViewById(R.id.task_price);

        checkBox = (CheckBox) view.findViewById(R.id.check_insurance);
        taskType = (Spinner) view.findViewById(R.id.type_spinner);
        releaseTask = (Button) view.findViewById(R.id.release_task);

        newRewords = new Rewords();
    }

    private void initEvent() {
        initImage(img1);

        setDeadDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager = getFragmentManager();
                if(date == null)
                    date = new Date();
                DatePickerFragment dialog = DatePickerFragment.NewInsance(date);
                dialog.setTargetFragment(page2Fragment.this, REQUEST_DATE);
                dialog.show(manager,DIALOG_DATE);
            }
        });

        setDeadTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager manager = getFragmentManager();
                if(date == null)
                    date = new Date();
                TimePickerFragment dialog = TimePickerFragment.newInstance(date);
                dialog.setTargetFragment(page2Fragment.this, REQUEST_TIME);
                dialog.show(manager, DIALOG_TIME);
            }
        });

        block1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null){

                    ImagePickerFragment dialog =ImagePickerFragment.NewInstace(1,mUser.getPhoneNum());
                    Log.i("back_task", "点击了方块"+1);
                    dialog.show(getFragmentManager(), "选择图片来源");
                }else {
                    Toast.makeText(getContext(), "请先登陆", Toast.LENGTH_SHORT).show();
                }
            }
        });

        block2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null){

                    ImagePickerFragment dialog =ImagePickerFragment.NewInstace(2,mUser.getPhoneNum());
                    Log.i("back_task", "点击了方块"+2);
                    dialog.show(getFragmentManager(), "选择图片来源");
                }else {
                    Toast.makeText(getContext(), "请先登陆", Toast.LENGTH_SHORT).show();
                }
            }
        });

        block3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null){

                    Log.i("back_task", "点击了方块"+imgStatus);
                    ImagePickerFragment dialog =ImagePickerFragment.NewInstace(3,mUser.getPhoneNum());
                    dialog.show(getFragmentManager(), "选择图片来源");
                }else {
                    Toast.makeText(getContext(), "请先登陆", Toast.LENGTH_SHORT).show();
                }
            }
        });

        block4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null){

                    Log.i("back_task", "点击了方块"+imgStatus);
                    ImagePickerFragment dialog =ImagePickerFragment.NewInstace(4,mUser.getPhoneNum());
                    dialog.show(getFragmentManager(), "选择图片来源");
                }else {
                    Toast.makeText(getContext(), "请先登陆", Toast.LENGTH_SHORT).show();
                }
            }
        });

//        setBlockOnclick(block1,1);
//        setBlockOnclick(block2,2);
//        setBlockOnclick(block3,3);
//        setBlockOnclick(block4,4);

        img1_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bitmap2!=null){
                    bitmap1 = bitmap2;
                    bitmap2 = null;
                    img1.setImageBitmap(bitmap1);
                    img1File = img2File;
                    img2File = null;
                    if(bitmap3!=null){
                        bitmap2 = bitmap3;
                        bitmap3 = null;
                        img2.setImageBitmap(bitmap2);
                        img2File = img3File;
                        img3File = null;
                        if(bitmap4!=null){
                            bitmap3 = bitmap4;
                            bitmap4 = null;
                            img3File = img4File;
                            img4File = null;
                            img3.setImageBitmap(bitmap3);
                            clearImg(img4_delete, img4, block4);
                        }else{
                            clearImg(img3_delete, img3, block3);
                            deleteImg( block4);
                        }
                    }else{
                        clearImg(img2_delete, img2, block2);
                        deleteImg( block3);
                    }
                }else{
                    clearImg(img1_delete, img1, block1);
                    deleteImg( block2);
                }
            }
        });

        img2_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bitmap3!=null){
                    bitmap2 = bitmap3;
                    bitmap3 = null;
                    img2File = img3File;
                    img3File = null;
                    img2.setImageBitmap(bitmap2);
                    if(bitmap4!=null){
                        bitmap3 = bitmap4;
                        bitmap4 = null;
                        img3File = img4File;
                        img4File = null;
                        img3.setImageBitmap(bitmap3);
                        clearImg(img4_delete, img4, block4);
                    }else{
                        clearImg(img3_delete, img3, block3);
                        deleteImg(block4);
                    }
                }else{
                    clearImg(img2_delete, img2, block2);
                    deleteImg( block3);
                }
            }
        });

        img3_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(bitmap4!=null){
                    bitmap3 = bitmap4;
                    bitmap4 = null;
                    img3File = img4File;
                    img4File = null;
                    img3.setImageBitmap(bitmap3);
                    clearImg(img4_delete, img4, block4);
                }else{
                    clearImg(img3_delete, img3, block3);
                    deleteImg(block4);

                }
            }
        });

        img4_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearImg(img4_delete, img4, block4);
                img4File = null;
            }
        });


        releaseTask.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null&&mUser.getUsrId()!=0){

                    String title = taskTitle.getText().toString().trim();
                    String content = taskContent.getText().toString().trim();
                    String price = taskPrice.getText().toString().trim();
                    if(title.length()==0 || content.length()==0 || price.length()==0 || time1==null || time2==null){
                        Toast.makeText(getContext(), "请填写完整的悬赏信息", Toast.LENGTH_SHORT).show();
                    }else{
                        taskTitle.setText("");
                        taskContent.setText("");
                        taskPrice.setText("");
                        checkBox.setChecked(false);
                        setDeadTime.setText("点击设置时间");
                        setDeadDate.setText("点击设置日期");


                        newRewords.setTaskType(taskType.getSelectedItemPosition());
                        newRewords.setUsrId(mUser.getUsrId());
                        newRewords.setTaskTitle(title);
                        newRewords.setTaskContent(content);
                        newRewords.setTaskType(taskType.getSelectedItemPosition());
                        newRewords.setBuyInsurance(checkBox.isChecked()?1:0);
                        newRewords.setPrice(Double.parseDouble(price));
                        String time = time1 + " " + time2;
                        /**查看时间*/
                        // Toast.makeText(getContext(), time, Toast.LENGTH_SHORT).show();
                        newRewords.setTaskDeadTime(time);
                        ResetImage();
                        newRewords.setTaskImg1Url(img1File);
                        newRewords.setTaskImg2Url(img2File);
                        newRewords.setTaskImg3Url(img3File);
                        newRewords.setTaskImg4Url(img4File);
                        new NetWorkService(getActivity(),RELEASE_TASK).uploadTask(newRewords,getContext());
                        //RewordList.getRewordList().getList().add(newRewords);
                        //newRewords = null;
                        //newRewords = new Rewords();
                    }
                }else{
                    Toast.makeText(getContext(), "请先登录", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void ResetImage() {

        bitmap1=null;
        bitmap2=null;
        bitmap3=null;
        bitmap4=null;

        img1_delete.setVisibility(View.GONE);
        img2_delete.setVisibility(View.GONE);
        img3_delete.setVisibility(View.GONE);
        img4_delete.setVisibility(View.GONE);
        initImage(img1);

        block1.setBackgroundColor(getActivity().getResources().getColor(R.color.whiteline));

        block1.setClickable(true);
        block2.setClickable(true);
        block3.setClickable(true);
        block4.setClickable(true);

        block2.setVisibility(View.GONE);
        block3.setVisibility(View.GONE);
        block4.setVisibility(View.GONE);

    }

    private void deleteImg(RelativeLayout block) {
        block.setVisibility(View.GONE);
    }

    private void clearImg(ImageView img_delete, ImageView img, RelativeLayout block) {
        img_delete.setVisibility(View.GONE);
        initImage(img);
        block.setClickable(true);
        block.setBackgroundColor(this.getResources().getColor(R.color.whiteline));
    }

    private void initImage(ImageView img) {
        params =  img.getLayoutParams();
        params.height = 100;
        params.width = 100;
        img.setLayoutParams(params);
        img.setImageResource(R.drawable.ic_add_msg);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityResult(int resquestCode, int resultCode, Intent data){
        if(resultCode != Activity.RESULT_OK){
            return ;
        }
        if(resquestCode == REQUEST_DATE){
            Date date = (Date) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            this.date = date;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            time1 = format.format(date);
            setDeadDate.setText(time1);
        }
        if(resquestCode == REQUEST_TIME){
            Date date = (Date) data.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
            this.date = date;
            SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
            time2 = format.format(date);
            setDeadTime.setText(time2);
        }
    }

    public void setBlockOnclick(RelativeLayout blockOnclick,int num) {
        RelativeLayout mBlockOnclick = blockOnclick;
        final int index = num;
        Log.i("back_task", "更新"+imgStatus);
        mBlockOnclick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mUser==null){
                    mUser = dataApp.getUser();
                }
                if(mUser!=null){

                    Log.i("back_task", "点击了方块"+imgStatus);
                    ImagePickerFragment dialog =ImagePickerFragment.NewInstace(index,mUser.getPhoneNum());
                    dialog.show(getFragmentManager(), "选择图片来源");
                }else {
                    Toast.makeText(getContext(), "请先登陆", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    @Override
    public void onAttach(Context context) {

        //动态注册广播接收器
        msgReceiver = new PublishBroadCast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.seth.myapplication.service.PUBLISH.TASK");
        context.registerReceiver(msgReceiver, intentFilter);
        super.onAttach(context);
    }

    @Override
    public void onResume() {

        Log.i("back_task", "onResume: 更新图片");
        updateImg();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(msgReceiver);
        super.onDestroy();
    }

    private void updateImg() {
        Log.i("back_task", "更新图片"+imgStatus);

        if(sBitmap != null){
            Log.i("back_task", "更新图片ing"+imgStatus);
            ImageView img;
            RelativeLayout realative = null;
            RelativeLayout next =null;
            switch (imgStatus){
                case 1:
                    img = img1;
                    bitmap1 = sBitmap;
                    realative = block1;
                    block2.setBackgroundColor(this.getResources().getColor(R.color.whiteline));
                    block2.setVisibility(View.VISIBLE);
                    block1.setBackgroundColor(this.getResources().getColor(R.color.fill_background));
                    img1_delete.setVisibility(View.VISIBLE);
                    initImage(img2);
                    img1File = sFile;
                    break;
                case 2:
                    img = img2;
                    bitmap2 = sBitmap;
                    realative = block2;
                    block2.setBackgroundColor(this.getResources().getColor(R.color.fill_background));
                    block3.setVisibility(View.VISIBLE);
                    block3.setBackgroundColor(this.getResources().getColor(R.color.whiteline));
                    img2_delete.setVisibility(View.VISIBLE);
                    initImage(img3);
                    img2File = sFile;
                    break;
                case 3:
                    img = img3;
                    bitmap3 = sBitmap;
                    realative = block3;
                    block3.setBackgroundColor(this.getResources().getColor(R.color.fill_background));
                    block4.setBackgroundColor(this.getResources().getColor(R.color.whiteline));
                    block4.setVisibility(View.VISIBLE);
                    img3_delete.setVisibility(View.VISIBLE);
                    initImage(img4);
                    img3File = sFile;
                    break;
                case 4:
                    img = img4;
                    bitmap4 = sBitmap;
                    realative = block4;
                    block4.setBackgroundColor(this.getResources().getColor(R.color.fill_background));
                    img4_delete.setVisibility(View.VISIBLE);
                    img4File = sFile;
                    break;
                default:
                    img =img1;
            }

            setNewImg(sBitmap,img);
            sBitmap = null;
            sFile = null;
            if(realative!=null)
                realative.setClickable(false);
            }
    }

    void setNewImg(Bitmap bitmap, ImageView img){
        params =  img.getLayoutParams();
        params.height = img.getMaxHeight();
        params.width = img.getMaxWidth();
        img.setLayoutParams(params);
        img.setImageBitmap(bitmap);
    }

    public void setFragment(Fragment fragment) {

        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        if(!fragment.isAdded()){    //如果当前fragment为被添加，则添加到Fragment管理器中
            transaction.hide(MainActivity.getContentFragment()).add(R.id.fragment_container, fragment).commit();
        }else{
            transaction.hide(MainActivity.getContentFragment()).show(fragment).commit();
        }

    }


    private class PublishBroadCast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String msg = intent.getStringExtra("result");
            if("success".equals(msg)){
                Fragment fragment = new ReleaseSuccess();
                setFragment(fragment);
            }else{
                Toast.makeText(context, "悬赏发布失败", Toast.LENGTH_SHORT).show();
            }

        }
    }
}
